<?php

namespace app\api\controller\jumpjump;

use app\admin\model\JumpjumpAcc;
use app\admin\model\JumpjumpShare;
use app\common\controller\Api;
use think\Request;
use app\admin\model\Xcx;

/**
 * 蹦蹦jump用户相关接口
 */
class Accs extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    // 登录接口
    public function login(Request $request)
    {
        $v = $request->post('version');
        $gh_id = $request->post('gh_id');
        $code = $request->post('code');

        $xcx = Xcx::get(['ghid' => $gh_id]);

        $url = 'https://api.weixin.qq.com/sns/jscode2session';
        $params['appid'] = $xcx['appid'];
        $params['secret'] = $xcx['secret'];
        $params['js_code'] = $code;
        $params['grant_type'] = 'authorization_code';

        $res = $this->http($url, $params);
        $json = json_decode($res, true);
        $openid = $json['openid'];

        if ($acc = JumpjumpAcc::get(['openid' => $openid])) {
            $data['user_id'] = $acc->id;
            $data['max_score'] = $acc->max_score;
            $data['money'] = $acc->money;
        } else {
            $a = new JumpjumpAcc;
            $a->openid = $openid;
            $a->max_score = 0;
            $a->save();
            $data['userid'] = $a->id;
            $data['max_score'] = 0;
            $data['money'] = 300;
        }

        $data['openid'] = $openid;
        $data['share_flag'] = true;

        if ($v == '0.9.9') {
            $data['share_flag'] = false;
        }

        $this->result('login', $data);
    }

    // 存储最高分
    public function save_max_score($openid, $max_score)
    {
        $acc = JumpjumpAcc::get(['openid' => $openid]);
        if ($acc) {
            $acc->max_score = $max_score;
            $res = $acc->save();
            $this->success($res);
        } else {
            $this->error(false);
        }
    }

    // 更新金钱变化
    public function update_money($openid, $money)
    {
        $acc = JumpjumpAcc::get(['openid' => $openid]);
        if ($acc) {
            $acc->money = $money;
            $res = $acc->save();
            $this->success($res);
        } else {
            $this->error(false);
        }
    }

    // 获取任务完成数据
    public function get_task_info($openid)
    {
        $data = array();
        if ($acc = JumpjumpShare::get(['fromUser' => $openid])) {
            array_push($data, $acc->position1 ? 1 : 0);
            array_push($data, $acc->position2 ? 1 : 0);
            array_push($data, $acc->position3 ? 1 : 0);
            array_push($data, $acc->position4 ? 1 : 0);
            array_push($data, $acc->position5 ? 1 : 0);
            array_push($data, $acc->position6 ? 1 : 0);
        } else {
            $a = new JumpjumpShare;
            $a->fromUser = $openid;
            $a->save();
            $data = array(0, 0, 0, 0, 0, 0);
        }

        $this->result('ok', $data);
    }
}